﻿using System.Collections.Generic;
using System.Linq;
using Apps.Web.Core;
using Apps.IBLL.PUB;
using Apps.Locale;
using System.Web.Mvc;
using Apps.Common;
using Apps.IBLL;
using Apps.Models.PUB;
using Microsoft.Practices.Unity;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Data;

namespace Apps.Web.Areas.PUB.Controllers
{
    public class SUPPLIERMETERIELController : BaseController
    {
        [Dependency]
        public IPUB_SUPPLIERMETERIELBLL m_BLL { get; set; }
        [Dependency]
        public IPUB_SUPPLIERBLL m_SUPPLIERBLL { get; set; }
        [Dependency]
        public IPUB_MATERIELBLL m_MaterielBLL { get; set; }
        ValidationErrors errors = new ValidationErrors();
        
        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName="Index")]
        public JsonResult GetList(GridPager pager, string queryStr,string parentId)
        {
            List<PUB_MATERIELModel> list = m_MaterielBLL.GetListBySupplierId(ref pager, parentId);
            GridRows<PUB_MATERIELModel> grs = new GridRows<PUB_MATERIELModel>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }
        #region 创建
        [SupportFilter]
        public ActionResult Create()
        {
         setNoPagerAscById.sort = "SUPPLIER_ID";
         ViewBag.SUPPLIER = new SelectList(m_SUPPLIERBLL.GetList(ref setNoPagerAscById, ""), "SUPPLIER_ID", "SUPPLIER_NAME");
            return View();
        }

        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult SaveMater(string SupplierID)
        {
            string inserted = Request["inserted"];
            string deleted = Request["deleted"];
            string updated = Request["updated"];
            string delErrors = "";
            string insErrors = "";
            int ret = 1;
            #region --删除数据--
            if (!string.IsNullOrWhiteSpace(deleted))
            {
                var deletedList = JsonConvert.DeserializeObject<List<PUB_MATERIELModel>>(deleted);
                List<string> delList = new List<string>();
                foreach (var item in deletedList)
                {
                    delList.Add(item.MATERIEL_ID);
                }

                ValidationErrors errors = new ValidationErrors();
                if (!m_BLL.Deletes(ref errors, a => delList.Contains(a.MATERIEL_ID) && a.SUPPLIER_ID==SupplierID))
                {
                    ret = 0;
                    delErrors = errors.Error;
                }
            }
            #endregion

            #region --新增数据--
            if (!string.IsNullOrWhiteSpace(inserted))
            {
                var insList = JsonConvert.DeserializeObject<List<PUB_MATERIELModel>>(inserted);
                List<PUB_SUPPLIERMETERIELModel> saveList=new List<PUB_SUPPLIERMETERIELModel>();
                foreach (var item in insList)
                {
                    PUB_SUPPLIERMETERIELModel SaveObj = new PUB_SUPPLIERMETERIELModel();
                    SaveObj.SUPPLIER_ID = SupplierID;
                    SaveObj.MATERIEL_ID = item.MATERIEL_ID;
                    saveList.Add(SaveObj);
                }

                try
                {
                    m_BLL.SaveImportData(saveList.AsEnumerable());
                }
                catch (Exception ex)
                {
                    ret = 0;
                    insErrors = ex.Message;
                }
            }
            #endregion


            return Json(JsonHandler.CreateMessage(ret, Resource.DeleteSucceed));
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Create(PUB_SUPPLIERMETERIELModel model)
        {
            model.SUPPLIER_ID = ResultHelper.NewId;
            if (model != null && ModelState.IsValid)
            {

                if (m_BLL.Create(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "SUPPLIER_ID" + model.SUPPLIER_ID + ",MATERIEL_ID" + model.MATERIEL_ID, "成功", "创建", "PUB_SUPPLIERMETERIEL");
                    return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "SUPPLIER_ID" + model.SUPPLIER_ID + ",MATERIEL_ID" + model.MATERIEL_ID + "," + ErrorCol, "失败", "创建", "PUB_SUPPLIERMETERIEL");
                    return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail));
            }
        }
        #endregion

        #region 修改
        [SupportFilter]
        public ActionResult Edit(string id)
        {
            PUB_SUPPLIERMETERIELModel entity = m_BLL.GetById(id);
         setNoPagerAscById.sort = "SUPPLIER_ID";
         ViewBag.SUPPLIER = new SelectList(m_SUPPLIERBLL.GetList(ref setNoPagerAscById, ""), "SUPPLIER_ID", "SUPPLIER_NAME");
            return View(entity);
        }

        [HttpPost]
        [SupportFilter]
        public JsonResult Edit(PUB_SUPPLIERMETERIELModel model)
        {
            if (model != null && ModelState.IsValid)
            {

                if (m_BLL.Edit(ref errors, model))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "SUPPLIER_ID" + model.SUPPLIER_ID + ",MATERIEL_ID" + model.MATERIEL_ID, "成功", "修改", "PUB_SUPPLIERMETERIEL");
                    return Json(JsonHandler.CreateMessage(1, Resource.EditSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "SUPPLIER_ID" + model.SUPPLIER_ID + ",MATERIEL_ID" + model.MATERIEL_ID + "," + ErrorCol, "失败", "修改", "PUB_SUPPLIERMETERIEL");
                    return Json(JsonHandler.CreateMessage(0, Resource.EditFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.EditFail));
            }
        }
        #endregion

        #region 详细
        [SupportFilter]
        public ActionResult Details(string id)
        {
            PUB_SUPPLIERMETERIELModel entity = m_BLL.GetById(id);
            return View(entity);
        }

        #endregion

        #region 删除
        [HttpPost]
        [SupportFilter]
        public ActionResult Delete(string id)
        {
            if(!string.IsNullOrWhiteSpace(id))
            {
                if (m_BLL.Delete(ref errors, id))
                {
                    LogHandler.WriteServiceLog(GetUserId(), "SUPPLIER_ID:" + id, "成功", "删除", "PUB_SUPPLIERMETERIEL");
                    return Json(JsonHandler.CreateMessage(1, Resource.DeleteSucceed));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "SUPPLIER_ID" + id + "," + ErrorCol, "失败", "删除", "PUB_SUPPLIERMETERIEL");
                    return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail + ErrorCol));
                }
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.DeleteFail));
            }
        }
        #endregion
        #region 导出导入
        [HttpPost]
        [SupportFilter]
        public ActionResult Import(string filePath)
        {
            var list = new List<PUB_SUPPLIERMETERIELModel>();
            bool checkResult = m_BLL.CheckImportData(Utils.GetMapPath(filePath), list, ref errors);
            //校验通过直接保存
            if (checkResult)
            {
                m_BLL.SaveImportData(list);
                LogHandler.WriteServiceLog(GetUserId(), "导入成功", "成功", "导入", "PUB_SUPPLIERMETERIEL");
                return Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed));
            }
            else
            {
                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog(GetUserId(), ErrorCol, "失败", "导入", "PUB_SUPPLIERMETERIEL");
                return Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol));
            }
        }
        [HttpPost]
        [SupportFilter(ActionName = "Export")]
        public JsonResult CheckExportData()
        {
            List<PUB_SUPPLIERMETERIELModel> list = m_BLL.GetList(ref setNoPagerAscById, "");
            if (list.Count().Equals(0))
            {
                return Json(JsonHandler.CreateMessage(0, "没有可以导出的数据"));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(1, "可以导出"));
            }
        }
        [SupportFilter]
        public ActionResult Export()
        {
            List<PUB_SUPPLIERMETERIELModel> list = m_BLL.GetList(ref setNoPagerAscById, "");
            JArray jObjects = new JArray();
                foreach (var item in list)
                {
                    var jo = new JObject();
                    jo.Add("SUPPLIER_ID", item.SUPPLIER_ID);
                    jo.Add("MATERIEL_ID", item.MATERIEL_ID);
                    jObjects.Add(jo);
                }
                var dt = JsonConvert.DeserializeObject<DataTable>(jObjects.ToString());
                var exportFileName = string.Concat(
                    "File",
                    DateTime.Now.ToString("yyyyMMddHHmmss"),
                    ".xlsx");
                return new ExportExcelResult
                {
                    SheetName = "Sheet1",
                    FileName = exportFileName,
                    ExportData = dt
                };
            }
        #endregion
        #region --主表查询--
        [HttpPost]
        [SupportFilter(ActionName="Index")]
        public JsonResult GetListParent(GridPager pager, string queryStr)
        {
            List<PUB_SUPPLIERModel> list = m_SUPPLIERBLL.GetAllPubSupplierb(ref pager);
            GridRows<PUB_SUPPLIERModel> grs = new GridRows<PUB_SUPPLIERModel>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }
        #endregion        
    }
}

